from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QTableView, QAbstractItemView, \
    QMenu, QAction

from data.pandasModel import PandasModel
from ui.edit_dialog import EditDialog
from utils.tools import showMessageBox


class TableView:
    def __init__(self, tableView:QTableView, parent):
        self.view = tableView
        self.parent = parent
        self.pandasModel = None
        self.view.setEditTriggers(QAbstractItemView.DoubleClicked)
        self.view.setContextMenuPolicy(Qt.CustomContextMenu)
        self.view.setSelectionMode(QAbstractItemView.ExtendedSelection)
        self.view.setSelectionBehavior(QAbstractItemView.SelectRows)
        self.view.customContextMenuRequested.connect(self.showContextMenu)

    def setModel(self, pandasModel:PandasModel):
        self.pandasModel = pandasModel
        current_ym = self.parent.getDate().toString("yyyy.M").split(".")
        self.pandasModel.setCurrentYM(current_ym)
        self.view.setModel(pandasModel)
        self.refreshSum()
        # 设置不同的列宽
        self.view.setColumnWidth(0, 120)
        self.view.setColumnWidth(1, 225)
        self.view.setColumnWidth(2, 50)
        self.view.setColumnWidth(3, 50)
        self.view.setColumnWidth(4, 75)
        self.view.setColumnWidth(5, 250)
        self.view.setColumnWidth(6, 100)

        self.parent.date.dateChanged.connect(self.filterByCurrentYM)
        self.parent.date.dateChanged.connect(self.refreshSum)

    def showContextMenu(self, pos):
        """
        当用户在表格视图上请求上下文菜单时显示菜单。

        参数:
        pos - 鼠标右键点击的位置。
        """
        # 获取选中的索引
        indexes = self.view.selectedIndexes()

        if not indexes:
            return

        menu = QMenu()

        # 删除选项
        delete_action = QAction("删除", self.view)
        delete_action.triggered.connect(lambda: self.deleteSelectedRows(indexes))
        menu.addAction(delete_action)

        # 修改选项
        modify_action = QAction("修改", self.view)
        modify_action.triggered.connect(lambda: self.modifySelectedRows(indexes))  # 这里可以添加修改功能的
        menu.addAction(modify_action)

        # 显示菜单
        menu.exec_(self.view.viewport().mapToGlobal(pos))

    def filterByCurrentYM(self):
        """
        根据当前月份过滤数据。
        """
        current_ym = self.parent.getDate().toString("yyyy.M").split(".")
        self.pandasModel.setCurrentYM(current_ym)

    def deleteSelectedRows(self, indexes):
        """
        删除选中的单元格所在的行。

        参数:
        selected_indexes - 选中的单元格索引列表。
        """
        # 获取所有选中的行号
        row_indices = set(index.row() for index in indexes)

        # 按照行号逆序删除行
        for row in sorted(row_indices, reverse=True):
            self.pandasModel.removeRow(row)

        # 更新总计和本月总计
        self.refreshSum()

        # 提示用户删除成功
        showMessageBox(f"已删除{len(row_indices)}行数据")

    def modifySelectedRows(self, indexes):
        row_indices = sorted(set(index.row() for index in indexes))
        if not row_indices:
            return

        # 获取选中行的数据
        rows_data = []
        headers = self.pandasModel.filtered_data.columns.tolist()
        for row in row_indices:
            rows_data.append([self.pandasModel.filtered_data.iloc[row][col] for col in headers])

        # 弹出编辑对话框
        dialog = EditDialog(rows_data, headers, self.view)
        if dialog.exec_():
            new_data = dialog.getData()

            # 更新模型数据
            for idx, row in enumerate(row_indices):
                for col, value in enumerate(new_data[idx]):
                    model_index = self.pandasModel.index(row, col)
                    self.pandasModel.setData(model_index, value)
            self.refreshSum()
            showMessageBox(f"已修改{len(row_indices)}行数据")
            # 是否打印
            if dialog.isPrintChecked():
                new_id = dialog.getID()
                old_id = self.parent["id"]
                self.parent.id.setText(new_id.zfill(8))

                cols = ["id", "name", "unit", "num", "unitPrice", "note", "price"]
                items = []
                for index, row in enumerate(new_data):
                    item = {}
                    for i in range(len(cols)):
                        item[cols[i]] = row[i]
                        if row[i] == "nan":
                            item[cols[i]] = ""
                        if cols[i] == "id":
                            item[cols[i]] = str(index + 1)

                    items.append(item)
                self.parent.controller.print(items)

                self.parent.id.setText(old_id)

    def refreshSum(self):
        sumPrice = self.pandasModel.sumAll()
        sumMonth = self.pandasModel.sumMonth(self.parent.getDate().toString("yyyy.M").split("."))
        self.parent.onRefreshSumUI(sumPrice, sumMonth)